package com.javatiaocao.myblog.controller;

import com.alibaba.fastjson.JSONObject;
import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.model.Article;
import com.javatiaocao.myblog.service.ArticleService;
import com.javatiaocao.myblog.service.TagService;
import com.javatiaocao.myblog.service.UserService;
import com.javatiaocao.myblog.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private TagService tagService;

    @Autowired
    private UserService userService;

    /**
     *
     *发表文章
     *
    * */
    @PostMapping("/publishArticle")
    public String publishArticle(Article article, String articleGrade,
                                 @AuthenticationPrincipal UserDetails userDetails, HttpServletRequest request){
        try {
            //获取文章作者
            String name = userDetails.getUsername();
            article.setAuthor(name);

            //标签

            String[] articleTags = request.getParameterValues("articleTagsValue");
            String[] newArticleTags = new String[articleTags.length + 1];
            for (int i = 0 ;i < articleTags.length ; i++) {
                newArticleTags[i] = articleTags[i].replaceAll("<br>", StringUtil.BLANK).replaceAll("$nbsp",StringUtil.BLANK)
                        .replaceAll("\\s",StringUtil.BLANK).trim();
            }
            newArticleTags[articleTags.length]=article.getArticleType();

            article.setArticleTags(StringAndArray.arrayToString(newArticleTags));


            //放入实体类
            tagService.insertTags(newArticleTags,Integer.parseInt(articleGrade));

            //生成文章摘要
            BuildArticleTabloidUtil buildArticleTabloidUtil = new BuildArticleTabloidUtil();
            article.setArticleTabloid(buildArticleTabloidUtil.buildArticleTabloid(
                    request.getParameter("articleHtmlContent")) + "....");

            //根据有无id判断修改或发布
            String id =(String) request.getSession().getAttribute("id");

            if(!StringUtil.BLANK.equals(id) && id != null){
                article.setId(Integer.parseInt(id));
                //修改文章
                DataMap dataMap =articleService.updateArticle(article);
                return JsonResult.build(dataMap).toJSON();
            }

            article.setOriginalAuthor(name);
            DataMap dataMap = articleService.publishArticle(article);

            return  JsonResult.build(dataMap).toJSON();
        }catch (Exception e){
            log.error("publishArticle Exception");
        }
        return JsonResult.fail(CodeType.PUBLISH_ARTICLE_NO_PERMISSION).toJSON();
    }


    /**
     *
     *  删除文章
     *
    **/
    @GetMapping("/deleteArticle")
    public String deleteArticle(Integer id){
        try {
            DataMap dataMap = articleService.deleteArticle(id);

            return JsonResult.build(dataMap).toJSON();

        }catch (Exception e){
            log.error("deleteArticle error");
        }

        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     *
     * 获取个人信息
     *
     * **/
    @PostMapping("/getUserPersonalInfo")
    public String getUserPersonalInfo(@AuthenticationPrincipal UserDetails userDetails){
        try {
//            JSONObject returnObject = new JSONObject();
            if (userDetails == null){
                return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
            }
//            returnObject.put("username",userDetails.getUsername());

            DataMap dataMap = userService.getUserPersonalInfo(userDetails.getUsername());

            return JsonResult.build(dataMap).toJSON();

        }catch (Exception e){
            log.error("getUserPersonalInfo error" + e);
        }

        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }

    /**
     *
     * 验证是否有权限写博客
     *
     * **/
    @GetMapping("/canYouWrite")
    public  String canYouWrite(@AuthenticationPrincipal UserDetails userDetails){
        try {
            DataMap dataMap = userService.canYouWrite(userDetails);

            return JsonResult.build(dataMap).toJSON();

        }catch (Exception e){
            log.error("deleteArticle error");
        }

        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }


    /**
     *
     * 获取文章草稿
     *
     * **/
    @GetMapping("/getDraftArticle")
    public String getDraftArticle(HttpServletRequest request){
        try {
            //获取文章id
            String getId =(String) request.getSession().getAttribute("id");
            if(getId != null){
                DataMap dataMap = articleService.getDraftArticle(Integer.parseInt(getId));
                return JsonResult.build(dataMap).toJSON();
            }

            //判断超时
            if(request.getSession().getAttribute("article") != null){
                String id =(String) request.getSession().getAttribute("id");
                if(!StringUtil.BLANK.equals(id) && id != null){
                    DataMap dataMap = articleService.getDraftArticle(Integer.parseInt(id));
                    request.getSession().removeAttribute("article");
                    request.getSession().removeAttribute("articleTags");
                    request.getSession().removeAttribute("articleGrade");
                    return JsonResult.build(dataMap).toJSON();
                }
            }

        }catch (Exception e){
            log.error("getDraftArticle error" + e);
        }

        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }


    /**
     *
     *
     * 获取文章详情
     *
     * **/
    @PostMapping("/getArticleByArticleId")
    public String getArticleByArticleId(long articleId){
        try {
            DataMap dataMap = articleService.getArticleByArticleId(articleId);

            return JsonResult.build(dataMap).toJSON();

        }catch (Exception e){
            log.error("getArticleDetail error"+e);
        }

        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }


}
